//
//  MZMessageViewController.m
//  minzuwenhuagong
//
//  Created by WANG CUNRUI on 14-5-23.
//  Copyright (c) 2014年 WANG CUNRUI. All rights reserved.
//

#import "MZMessageViewController.h"
#define SY @"http://210.30.0.167:6162/whg2/Zhanlan/findAllZX?p="

static NSString *ID = @"MyCell";
static int count;

@interface MZMessageViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) NSMutableArray *currentdata;
@property (nonatomic) NSInteger countp;
@property (strong,nonatomic) NSString *imagePath;
@property (strong, nonatomic) NSData *data;
@property (strong,nonatomic) UIButton *tabbut;
@property (strong,nonatomic) UIImage *image;
@property (nonatomic) BOOL flag;
@property (nonatomic) BOOL flag1;
@end

@implementation MZMessageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}


- (void)reachabilityChanged:(NSNotification *)note {
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    NetworkStatus status = [curReach currentReachabilityStatus];
    self.isReachable = YES;
    if (status == NotReachable) {
        
        self.isReachable = NO;
    }
    else
    {
        self.isReachable = YES;
    }
    
    
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    [self cache];
    self.view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    // 1. tableView
    CGRect frame = self.view.bounds;
    
    UITableView *messageView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height - 28) style:normal];
    // 1) 数据源
    [messageView setDataSource:self];
    // 2) 代理
    [messageView setDelegate:self];
    // 3) 设置表格高度
//    [messageView setRowHeight:165];
    // 4) 设置分隔线
//    UIImageView * imagearrow = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrooww.png"]];
//    imagearrow.frame = CGRectMake(300, 0, 30, 30);
//    [self.view addSubview:imagearrow];
//    _tabbut = [UIButton buttonWithType:UIButtonTypeCustom];
//    [_tabbut setBackgroundColor:[UIColor whiteColor]];
//    [_tabbut setBackgroundImage:[UIImage imageNamed:@"arrooww.png"]
//                      forState:UIControlStateNormal];
//    [_tabbut addTarget:self action:@selector(bbiClick:)
//     forControlEvents:UIControlEventTouchUpInside];
//    _tabbut.frame = CGRectMake(280, 4, 40, 40);
//    [self.navigationController.navigationBar addSubview:_tabbut];
//    UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithCustomView:_tabbut];
//    self.navigationItem.rightBarButtonItem = menuButton;
//    [messageView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
//    UIBarButtonItem *rightBBI = [[UIBarButtonItem alloc] initWithTitle:@"关于" style:UIBarButtonItemStylePlain target:self action:@selector(bbiClick:)];
//    rightBBI.tag = 1;
//    self.navigationItem.rightBarButtonItem = rightBBI;

    
    [self.view addSubview:messageView];
    self.messageView = messageView;

    [self.messageView registerClass:[MZMessageCell class] forCellReuseIdentifier:ID];
    [self Reshing];
    [self setupRefresh];
    
    
    
}

//- (void)viewWillAppear:(BOOL)animated
-(void)cache
{
//    [super viewWillAppear:animated];
    hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    [hostReach startNotifier];
    NSParameterAssert([hostReach isKindOfClass: [Reachability class]]);
    NetworkStatus status = [hostReach currentReachabilityStatus];
    self.isReachable = YES;
    if (status == NotReachable) {
        
        self.isReachable = NO;
    }
    else
    {
        self.isReachable = YES;
    }
    _flag = YES;
    _flag1 = NO;
    //如果NSUserDefaults中没有HomePageLastUpdate，则设置其初始值。
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"HomePageLastUpdate"]) {
        [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"HomePageLastUpdate"];
    }
    
    
    //获取全局变量
    MZAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSURL *productURL = [NSURL URLWithString:@"http://210.30.0.167:6162/mzserver/Zhanlan/findAllZX?p=1"];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:productURL];
    request.delegate = self;
    [request setDownloadCache:appDelegate.myCache];
    [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
    NSLog(@"it%hhd",self.isReachable);
    //判断刷新时间间隔
    if ([MZTool IsNeedUpdate:@"HomePageLastUpdate"]) {
        
        //只有在网络状态连通，且满足刷新时间间隔的情况下，request才不读缓存中的内容。
        //如果目前网络状态连通
        if (self.isReachable) {
            
            [request setCachePolicy:ASIDoNotReadFromCacheCachePolicy];
            
        }
        [request startAsynchronous];
        NSLog(@"主页下载中");
    }
    else
    {
        [request startAsynchronous];
        _flag1 = YES;
    }
    if ((self.isReachable == NO)&&(_flag == YES)) {
        [request requestFinished];
        if ((_flag1 == NO)&&([request downloadCache])) {
            //            UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"33数据加载失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
            //            [result show];
        }
        
    }
    
    
}


- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.messageView addHeaderWithTarget:self action:@selector(headerRereshing)];
    
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.messageView addFooterWithTarget:self action:@selector(footerRereshing)];
}



#pragma mark - 加载JSON

-(void)Reshing
{
    _countp = 2;
    count = 2;
    NSURL *urls = [NSURL URLWithString:@"http://210.30.0.167:6162/mzserver/Zhanlan/findAllZX?p=1"];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:urls];
    //request.delegate = self;

        [request startSynchronous];
        NSLog(@"下载产品数据中");
        NSError *error = [request error];
        if (!error) {
            _currentdata = [[request responseData]JSONValue];
            if (_currentdata == nil) {
                MZAppDelegate *appDlg = (MZAppDelegate *)[[UIApplication sharedApplication] delegate];
                    if(appDlg.isReachable)
                    {
                        [self headerRereshing];
                    }
                    else
                    {
                        UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"数据加载失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
                        [result show];
                        NSLog(@"网络连接异常");//执行网络异常时的代码
                    }
            }else{
            
            [self.messageView reloadData];
            }
        }
        else{
//            MZAppDelegate *appDlg = (MZAppDelegate *)[[UIApplication sharedApplication] delegate];
//            if ([[NSUserDefaults standardUserDefaults] objectForKey:@"HomePageLastUpdate"] == nil) {
//                UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"加载数据失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
//                [result show];
////                [self.messageView headerBeginRefreshing];
//            }
            
        }
        //[self.messageView headerEndRefreshing];
}

- (void)headerRereshing
{
    NSURL *urls = [NSURL URLWithString:@"http://210.30.0.167:6162/mzserver/Zhanlan/findAllZX?p=1"];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:urls];
    //request.delegate = self;
        // 给数据列表赋值
    // 2.1.5秒后刷新表格U}
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [request startSynchronous];
        NSLog(@"下载产品数据中");
        NSError *error = [request error];
        if (!error) {
            _currentdata = [[request responseData]JSONValue] ;
            [self.messageView reloadData];
        }
        else{
            UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"数据加载失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
            [result show];
        }
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.messageView headerEndRefreshing];
    });
}






#pragma mark - 注册单元格

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 165;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_currentdata count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1. 使用可重用标示符查询可重用单元格
    MZMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    NSDictionary *dic = _currentdata[indexPath.row];
    NSString *pic = [dic objectForKey:@"PIC_PATHS"];
    cell.textLabel.text = [dic objectForKey:@"TIME"];
    cell.detailTextLabel.text =[dic objectForKey:@"TITLE"];
    NSLog(@"%@",cell.detailTextLabel.text);
        NSRange foundObj = [pic rangeOfString :@";" options:NSCaseInsensitiveSearch];
        if(foundObj.length>0)
        {
            NSRange range = [pic rangeOfString:@";"];
            NSString *b = [pic substringToIndex:range.location];
            
            NSString *imagePath = [NSString stringWithFormat:@"http://www.mzdigital.cn/%@", b];
            
            _imagePath = imagePath;
        }else
        {
            NSString *imagePath = [NSString stringWithFormat:@"http://www.mzdigital.cn/%@", pic];
            
            _imagePath = imagePath;
        }
        //检测地址是否含有两张图片，有则取分号前一张
        [cell.imageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_imagePath]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    
    return cell;
}


- (void)startRefresh:(int)count
{
    NSString *str = [NSString stringWithFormat:@"http://210.30.0.167:6162/mzserver/Zhanlan/findAllZX?p=%ld",(long)count];
    
    NSURL *url = [NSURL URLWithString:str];
    NSLog(@"url2 = %@",url);

    // 2. 建立NSURLRequest
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    //request.delegate = self;
    [request startSynchronous];
    //    _currentdata = [NSMutableArray array];
    NSLog(@"current2 = %lu",(unsigned long)_currentdata.count);
    NSLog(@"下载产品数据中");
    NSError *error = [request error];
    if (!error) {
        NSData *data = [request responseData];
//        NSLog(@"data2=%@",data.JSONValue );
        NSMutableArray *ARRAY = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSMutableArray *currentarray = [[NSMutableArray alloc]init];
        [currentarray addObjectsFromArray:_currentdata];
        [currentarray addObjectsFromArray:ARRAY];
        _currentdata = currentarray;
//        NSLog(@"array = %@",ARRAY);
        NSLog(@"current2.1 = %lu",(unsigned long)_currentdata.count);
    
        if (![ARRAY  isEqual: @[]]) {
            NSLog(@"success");
            _countp = _countp + 1;
            count = count + 1;
            
            NSLog(@"count11 = %ld",(long)count);
            
        }
        NSLog(@"count = %ld",(long)count);
        _countp = count;
        NSLog(@"datalist2 = %@",self.dataList);
        // 刷新表格
        [self.messageView reloadData];
    }else{
        UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"数据加载失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
        [result show];
    }
}

- (void)footerRereshing
{
    count = _countp;
    
    if ((_currentdata != nil)) {
        
        NSLog(@"count22 = %ld",(long)count);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //            [self startRefresh:_countp];
            [self startRefresh:count];
            // 刷新表格
            [self.messageView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.messageView footerEndRefreshing];
            
        });
    }else{
        UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"数据加载失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
        [result show];
    }
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.messageView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.messageView footerEndRefreshing];
    });
}


-(void)cachetwo:(NSURL*)url
{
    MZAppDelegate *appDelegate1 = [[UIApplication sharedApplication] delegate];
    
    NSURL *productURL = url;
    ASIHTTPRequest *request1 = [[ASIHTTPRequest alloc] initWithURL:productURL];
    request1.delegate = self;
    [request1 setDownloadCache:appDelegate1.myCache];
    [request1 setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
    NSLog(@"it%hhd",self.isReachable);
    //判断刷新时间间隔
    if ([MZTool IsNeedUpdate:@"HomePageLastUpdate"]) {
        
        //只有在网络状态连通，且满足刷新时间间隔的情况下，request才不读缓存中的内容。
        //如果目前网络状态连通
        if (self.isReachable) {
            
            [request1 setCachePolicy:ASIDoNotReadFromCacheCachePolicy];
            
        }
        [request1 startAsynchronous];
        NSLog(@"主页下载中");
    }
    else
    {
        [request1 startAsynchronous];

    }
    
    

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _messageDetailedView = [[MZMessageDetailedViewController alloc] init];
    NSDictionary *dic = _currentdata[indexPath.row];
    _messageDetailedView.messageTitle = [dic objectForKey:@"TITLE"];
    _messageDetailedView.messageTime = [dic objectForKey:@"TIME"];
    _messageDetailedView.messageDept = [dic objectForKey:@"DEPT"];
    _messageDetailedView.messageContent = [dic objectForKey:@"CONTENTS"];
    _messageDetailedView.messageID = [dic objectForKey:@"ZHANLAN_ID"];
    _messageDetailedView.messagePic = [dic objectForKey:@"PIC_PATHS"];

    [self.navigationController pushViewController:_messageDetailedView animated:YES];
     
}



- (void)requestFinished:(ASIHTTPRequest *)request
{
    _currentdata = [[request responseData] JSONValue];
    if ((self.isReachable == NO)&&(_currentdata == nil)) {
        
        _flag1 = !_flag1;
    }

    [self.messageView reloadData];
    //判断数据来源并决定是否刷新数据更新时间
    if ([request didUseCachedResponse] == NO) {
        [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"HomePageLastUpdate"];
        NSLog(@"数据来自服务器,首页下载成功");
    }
    else
    {
        NSLog(@"数据来自缓存,首页下载成功");
    }
}

//- (void)bbiClick:(UIButton *)bbi
//{
//    _guanyuController = [[guanyuController alloc] init];
//    [self.navigationController pushViewController:_guanyuController animated:YES];
//}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"数据加载失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
    [result show];

}

-(void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
